package com.rainwen.zookeeper.client;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.GetChildrenBuilder;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * Created by rain.wen on 2017/8/4.
 */
public class ZkUtils {

    public static Pattern p = Pattern.compile("/");

    public static CuratorFramework createClient(String zookeeperConnectionString) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
        client.start();
        return client;
    }

    public static void close(CuratorFramework client) {
        client.close();
    }

    /**
     * 递归输出所有节点
     * @param client
     * @throws Exception
     */
    public static void recursionAllPathAndData(CuratorFramework client) throws Exception {
        GetChildrenBuilder getChildrenBuilder = client.getChildren();
        recursion(getChildrenBuilder, "", "/");
    }

    private static void recursion(GetChildrenBuilder getChildrenBuilder, String parentPath, String path) throws Exception {
        String currPath = "";
        if(parentPath.equals("")){
            currPath = path;
        } else if(parentPath.equals("/")) {
            currPath = "/" +path;
        }else {
            currPath = parentPath + "/" + path;
        }

        List<String> childPaths = getChildrenBuilder.forPath(currPath);
        if(childPaths.size() == 0) {
            return;
        }

        for (String child : childPaths) {
            System.out.println(getSplitChar(currPath) + child);
            recursion(getChildrenBuilder, currPath, child);
        }
    }

    private static String getSplitChar(String currPath) {
        int size = getMatchSize(currPath);
        if(size == 1){
            return "|-";
        } else if(size == 2){
            return "  |-";
        } else if(size == 3){
            return "   |-";
        } else if(size == 4){
            return "    |-";
        } else if(size == 5){
            return "     |-";
        } else if(size == 6){
            return "      |-";
        } else if(size == 7){
            return "       |-";
        } else if(size == 8){
            return "        |-";
        }
        return "|-";
    }

    /**
     * 匹配个数
     *
     * @param str
     * @return
     */
    public static int getMatchSize(String str) {
        int size = 0;
        Matcher m = p.matcher(str);
        boolean result = m.find();
        while(result){
            size ++;
            result = m.find();
        }
        return size;
    }

}
